<template>
  <div>
    <el-card shadow="never">
      <el-button icon="el-icon-document-add" type="primary" @click="handleAdd"
        >添加</el-button
      >
    </el-card>

    <el-table
      :data="tableData"
      border=""
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
    >
      <el-table-column label="Id">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型">
        <template slot-scope="scope">
          <span>{{ scope.row.qrcode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片">
        <template slot-scope="scope">
          <img :src="localhostPath + scope.row.qrcodePath" alt="" width="100%" height="100%"/>
        </template>
      </el-table-column>
      <el-table-column label="是否启用">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isEnable"
            @change="change(scope.$index, scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            title="确定删除吗？"
            @confirm="handleDelete(scope.$index, scope.row)"
          >
            <el-button size="mini" type="danger" slot="reference"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 对话框 -->
    <el-dialog title="二维码" :visible.sync="dialogFormVisible" width="500px">
      <el-form :model="form">
        <el-form-item label="二维码类型名称" :label-width="formLabelWidth">
          <el-input v-model="form.qrcode" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="上传二维码图片" :label-width="formLabelWidth">
          <el-upload
            :class="{ hide: hideUpload }"
            ref="upload"
            action="#"
            accept="image/png,image/gif,image/jpg,image/jpeg"
            list-type="picture-card"
            :limit="1"
            :auto-upload="false"
            :before-upload="handleBeforeUpload"
            :on-change="handleChange"
            :on-remove="removeFile"
            :file-list="listarr"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <my-cropper
            ref="myCropper"
            @getFile="getFile"
            @upAgain="upAgain"
          ></my-cropper>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MyCropper from "../components/cropper.vue";
import {
  addQrCode,
  getQrCode,
  IsEnableCode,
  editQrCode,
  deleteQrCode,
} from "../api/web";
// import { deletePicture } from "../api/article";
import common from "../utils/common";

export default {
  components: { MyCropper },
  data() {
    return {
      //当图片上传一张后就隐藏上传框
      hideUpload: false,
      limitCount: 1,
      //后端全局路径
      localhostPath: common.localhostPath,
      dialogFormVisible: false,
      tableData: [],
      form: {
        qrcode: "",
        qrcodePath: "",
        isEnable: true,
      },
      formLabelWidth: "120px",
      dialogVisible: false,
      listarr: [],
      // picForm: {
      //   picPath: "",
      // },
      newIndex: "",
    };
  },
  methods: {
    //编辑
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      this.form = row;
      this.newIndex = index;
      this.listarr = [];
      this.hideUpload = false;
    },
    handleDelete(index, row) {
      console.log(index, row);
      deleteQrCode(row.id).then(({ data }) => {
        this.tableData.splice(index,1);
        this.$message.success(data.msg);
      });
    },
    //添加
    handleAdd() {
      this.dialogFormVisible = true;
      this.form = {};
      this.listarr = [];
      this.hideUpload = false;
    },
    //上传图片触发
    handleCrop(file) {
      this.$nextTick(() => {
        this.$refs.myCropper.open(file.raw || file, 200, 200, 1, 1);
      });
    },
    // 点击弹框重新时触发
    upAgain() {
      this.$refs["upload"].$refs["upload-inner"].handleClick();
    },
    // 获取裁剪后的图片
    getFile(file) {
      this.$nextTick(() => {
        this.$refs.myCropper.close();
      });
      var url = window.URL.createObjectURL(file);
      this.listarr.push({ name: file.name, url: url, file: file });
    },
    handleChange(file, fileList) {
      console.log(fileList);
      this.hideUpload = true;
      if (fileList.length > 0) {
        this.photoList = [fileList[fileList.length - 1]];
      }
      this.handleCrop(file);
    },
    handleBeforeUpload(file) {
      console.log("before");
      if (
        !(
          file.type === "image/png" ||
          file.type === "image/gif" ||
          file.type === "image/jpg" ||
          file.type === "image/jpeg"
        )
      ) {
        this.$notify.warning({
          title: "警告",
          message:
            "请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片",
        });
      }
      let size = file.size / 1024 / 1024 / 2;
      if (size > 2) {
        this.$notify.warning({
          title: "警告",
          message: "图片大小必须小于2M",
        });
      }
    },
    confirm() {
      if (this.form.id == undefined) {
        //添加二维码
        var name = this.form.qrcode;
        if (name != undefined && this.listarr.length >0) {
          const fileObj = this.listarr[0].file;
          const form1 = new FormData();
          form1.append("imageFile", fileObj);
          form1.append("codeName", name);
          addQrCode(form1).then(({ data }) => {
            console.log(data);
            if (data.code == 200) {
              this.tableData.push(data.data);
              this.$message.success(data.msg);
            } else {
              this.$message.error(data.msg);
            }
            this.dialogFormVisible = false;
          });
        } else {
          this.$message.error("二维码的类型名称或图片不能为空");
        }
      } else {
        //编辑二维码
        var qrname = this.form.qrcode;
        // this.picForm.picPath = "/" + this.form.qrcodePath;
        // deletePicture(this.picForm).then((data) => {
        //   console.log(data);
        // });
        if (qrname != undefined  && this.listarr.length >0) {
          const fileObj = this.listarr[0].file;
          const form1 = new FormData();
          form1.append("imageFile", fileObj);
          form1.append("codeName", qrname);
          editQrCode(this.form.id, form1).then(({ data }) => {
            console.log(data);
            console.log(data.data.qrcodePath);
            this.tableData.splice(this.newIndex, 1, data.data);
          });
        } else {
          this.$message.error("二维码的类型名称或图片不能为空");
        }

        this.dialogFormVisible = false;
      }

      //确认
    },
    //删除图片时将fileList清空
    removeFile() {
      this.listarr = [];
      this.hideUpload = false;
    },
    //是否启用二维码
    change(index, row) {
      console.log(index, row);
      this.form.isEnable = row.isEnable;
      IsEnableCode(row.id, this.form).then(({ data }) => {
        console.log(data);
      });
    },
  },
  mounted() {
    getQrCode().then(({ data }) => {
      this.tableData = data.data;
      console.log(this.tableData);
    });
  },
};
</script>

<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>